<template>
  <div>
    <!-- 左边外层容器 -->
    <el-container>
      <!--侧边栏点击事件 -->
      <el-aside :style="{ width: isCollapse ? 'auto' : '200px' }">
        <navbar :menus="menus" :collapse="isCollapse"></navbar>
      </el-aside>

      <!-- 右边外层容器 -->
      <el-container>
        <!-- 头部 -->
        <el-header>
          <i
            class="el-collapse"
            :class="isCollapse ? 'el-icon-s-unfold' : 'el-icon-s-fold'"
            @click="handleCollapse"
          ></i>
        </el-header>
        <!-- 主体 -->
        <el-main>
          <router-view></router-view>
        </el-main>
        <!-- 脚 -->
        <el-footer>桂ICP备2020009447号</el-footer>
      </el-container>
    </el-container>
  </div>
</template>

<script>
import routes from "../router/routers";
import Navbar from "../components/Navbar";
export default {
  //注册组件
  components: {
    Navbar,
  },
  data() {
    return {
      isCollapse: false,
    };
  },

  //解决导航栏路由的问题
  methods: {
    resolve(arr, parentpath = "") {
      let newArr = [];

      //第一步遍历数组的每一个元素
      arr.forEach((route) => {
        let obj = Object.assign({}, route);

        //当上级路径存在，并且最后一位不为/，则后面添加/
        parentpath =
          parentpath && parentpath.lastIndexOf("/") != parentpath.length - 1
            ? parentpath + "/"
            : parentpath;

        //路径总是给加上父级路径
        obj.path = parentpath + obj.path;

        //第二步 判断有没有children属性：有则需要再处理；如没有则直接push到一个新数组中
        if (obj.children && obj.children.length > 0) {
          obj.children = this.resolve(obj.children, obj.path);
        }

        //第三步 如果当前路由有hidden属性，那么就将其子节点提升上来
        if (obj.meta && obj.meta.hidden) {
          if (obj.children && obj.children.length > 0) {
            obj.children.forEach((item) => {
              let tmp = Object.assign({}, item);
              newArr.push(tmp);
            });
          }
        } else {
          newArr.push(obj);
        }
      });
      return newArr;
    },

    //折叠导航栏组件
    handleCollapse() {
      this.isCollapse = !this.isCollapse;
    },
  },
  computed: {
    menus() {
      let arr = this.resolve(routes);

      return arr;
    },
  },
};
</script>

<style scoped>
.el-header {
  background-color: rgb(28, 143, 236);
  display: flex;
  align-items: center;
}
.el-main {
  background-color: rgb(250, 252, 180);
  height: calc(100vh - 120px);
  overflow-y: scroll;
}
.el-footer {
  background-color: gainsboro;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 10px;
}
.el-collapse {
  font-size: 2rem;
}
</style>
